package com.seu.project.seuquiz.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seu.project.seuquiz.annotation.AuthCheck;
import com.seu.project.seuquiz.common.BaseResponse;
import com.seu.project.seuquiz.common.DeleteRequest;
import com.seu.project.seuquiz.common.ErrorCode;
import com.seu.project.seuquiz.common.ResultUtils;
import com.seu.project.seuquiz.exception.BusinessException;
import com.seu.project.seuquiz.model.converter.UserQuestionMapConverter;
import com.seu.project.seuquiz.model.dto.question.QuestionQueryRequest;
import com.seu.project.seuquiz.model.dto.userQuestionMap.UserQuestionMapAddRequest;
import com.seu.project.seuquiz.model.dto.userQuestionMap.UserQuestionMapQueryRequest;
import com.seu.project.seuquiz.model.dto.userQuestionMap.UserQuestionMapUpdateRequest;
import com.seu.project.seuquiz.model.entity.Contest;
import com.seu.project.seuquiz.model.entity.Question;
import com.seu.project.seuquiz.model.entity.UserQuestionMap;
import com.seu.project.seuquiz.model.req.UserQuestionReq;
import com.seu.project.seuquiz.model.vo.UserQuestionVO;
import com.seu.project.seuquiz.service.QuestionService;
import com.seu.project.seuquiz.service.UserQuestionMapService;
import com.seu.project.seuquiz.util.EasyExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import nonapi.io.github.classgraph.json.JSONUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 用户及其做题接口
 * @author SoftPro
 * @createDate: 2023-07-16 09:48
 */
@RestController
@RequestMapping("/user_question")
@Api(tags = "用户-题目接口")
@Slf4j
public class UserQuestionMapController {
    

    @Resource
    private UserQuestionMapService userQuestionMapService;

    @Resource
    private QuestionService questionService;

    // region_start 基本增删改查

    /**
     * 新增用户和题目
     * @param request
     * @return
     */
    @PostMapping("/add")
    @ApiOperation("addUserQuestion: 用户新做了一道题目")
    public BaseResponse<Long> addUserQuestion(@RequestBody UserQuestionMapAddRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Integer score = request.getScore();

        String studentId = request.getStudentId();
        String questionId = request.getQuestionId();

        long id = userQuestionMapService.userQuestionMapAdd(studentId, questionId, score > 0);
        return ResultUtils.success(id);
    }

    /**
     * 删除用户和题目
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = "admin")
    @ApiOperation(" deleteUserQuestionById: 删除用户做题记录")
    public BaseResponse<Boolean> deleteUserQuestionById(@RequestBody DeleteRequest deleteRequest){
        if(deleteRequest==null || deleteRequest.getId()<0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userQuestionMapService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 批量删除
     * @param deleteRequest
     * @return
     */
    @PostMapping("/deleteByIds")
    @AuthCheck(mustRole = "admin")
    @ApiOperation("deleteUserQuestionByIds: 批量删除用户做题记录")
    public BaseResponse<Boolean> deleteUserQuestionByIds(@RequestBody DeleteRequest deleteRequest){
        if(deleteRequest==null || deleteRequest.getIds().size() < 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userQuestionMapService.removeByIds(deleteRequest.getIds());
        return ResultUtils.success(b);
    }

    /**
     * 更新用户及题目
     * @param updateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = "admin")
    @ApiOperation("updateUserQuestion: 更新用户做题记录")
    public BaseResponse<String> updateUserQuestion(@RequestBody UserQuestionMapUpdateRequest updateRequest){
/*        if(updateRequest==null || updateRequest.getId()<0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserQuestionMap oldRecord = userQuestionMapService.getById(updateRequest.getId());
        boolean b = userQuestionMapService.updateById(UserQuestionMapConverter.userQuestionMapQueryRequestToUserQuestionMap(updateRequest));*/
        return ResultUtils.success("业务暂时不支持更新");
    }

    /**
     * 根据id查询用户和题目
     * @param id
     * @return
     */
    @GetMapping("/get")
    @ApiOperation("updateUserQuestion: 根据id查询用户和题目")
    public BaseResponse<UserQuestionVO> getUserQuestionById(int id){
        if(id<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 根据id获取用户题目
        UserQuestionMap userQuestionMap = userQuestionMapService.getById(id);
        String questionId = userQuestionMap.getQuestionId();
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "题目不存在或已被删除");
        }
        return ResultUtils.success(UserQuestionVO.toModel(userQuestionMap, question));
    }


    /**
     * 根据查询条件获取全部的用户和题目信息  todo: 待测试
     * @param request
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("listUserQuestion: 根据查询条件获取全部的用户和题目信息")
    public BaseResponse<List<UserQuestionVO>> listUserQuestion(UserQuestionReq request) {
        return ResultUtils.success(getByReq(request));
    }

    private List<UserQuestionVO> getByReq(UserQuestionReq request) {
        String questionType = request.getQuestionType();
        String type = request.getType();
        QueryWrapper<Question> questionWrapper = questionService.getQueryWrapper(QuestionQueryRequest.builder()
                .questionType(questionType)
                .type(type)
                .build());
        // 根据筛选条件获得所有的题目
        List<Question> questions = questionService.list(questionWrapper);
        // 把题目包装成map形成
        Map<Long, Question> collectMap = questions.stream()
                .collect(Collectors.toMap(Question::getId, Function.identity(), (a, b) -> a));

        QueryWrapper<UserQuestionMap> queryWrapper =
                userQuestionMapService.getQueryWrapper(UserQuestionReq.toQueryRequest(request, collectMap.keySet()));
        // 根据题目ids 和 userid 查询用户题目
        List<UserQuestionMap> list = userQuestionMapService.list(queryWrapper);

        return list.stream()
                .map(it -> UserQuestionVO.toModel(it, collectMap.get(Long.parseLong(it.getQuestionId()))))
                .collect(Collectors.toList());
    }

    /**
     * 分页获取用户和题目     todo:待测试
     * @param request
     * @return
     */
    @GetMapping("/list/page")
    @ApiOperation("listUserQuestionByPage: 根据查询条件获取分页的用户和题目信息")
    public BaseResponse<Page<UserQuestionVO>> listUserQuestionByPage(UserQuestionReq request) {
        long current = 1;
        long size = 10;
        if (request != null) {
            current = request.getCurrent();
            size = request.getPageSize();
        }
        List<UserQuestionVO> list = getByReq(request);
        List<UserQuestionVO> records = list.stream().skip((current - 1) * size).limit(size).collect(Collectors.toList());
        Page<UserQuestionVO> page = new Page(current, size);
        page.setTotal(list.size());
        page.setRecords(records);
        return ResultUtils.success(page);
    }

    // region_end

    /**
     * 以excel文件方式批量添加学生题目
     * @param multipartFile
     * @return
     */
    @PostMapping("/add/batch")
    public BaseResponse<String> addContestBatch(@RequestPart("file") MultipartFile multipartFile){
        // 校验文件
        long size = multipartFile.getSize();
        String originalFilename = multipartFile.getOriginalFilename();
        // 校验文件大小
        final long ONE_MB = 1024 * 1024L;
        if (size > ONE_MB) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件超过 1M");
        }
        // 校验文件后缀   aaa.png
        String suffix = FileUtil.getSuffix(originalFilename);
        final List<String> validFileSuffixList = Arrays.asList("xlsx", "xls");
        if (!validFileSuffixList.contains(suffix)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件后缀非法");
        }

        List<UserQuestionMap> userQuestionMapList = EasyExcelUtils.excelToUserQuestionList(multipartFile);
        boolean saveBatch = userQuestionMapService.saveBatch(userQuestionMapList);
        if (!saveBatch) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "数据库错误");
        }
        return ResultUtils.success("添加完成");
    }
}
